package com.c5c7.dao;

import com.c5c7.bean.NewsBeam;
import com.c5c7.util.DBConnection;

import java.util.Date;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class NewsDao {
    DBConnection DBConn= new DBConnection();
    public List<NewsBeam> getList(){
        // todo 后期添加分页功能
        Connection conn = DBConn.getConn();
        String sql = "select * from news";
        List<NewsBeam> list = new ArrayList<NewsBeam>();
        list = null;

        try {
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()){
                NewsBeam newsBeam = new NewsBeam();
                newsBeam.setNewsID(rs.getInt("NewsID"));
                newsBeam.setNewsTitle(rs.getString("NewsTitle"));
                newsBeam.setNewsContent(rs.getString("NewsContent"));
                newsBeam.setNewsTime(rs.getString("NewsTime"));
                newsBeam.setAdminName(rs.getString("AdminName"));
                list.add(newsBeam);
            }
        } catch (SQLException e) {
            throw new RuntimeException();
        }
        return list;
    }

    /**
     * 添加新闻
     * @param news
     * @return
     */
    public int add(NewsBeam news){
        Connection conn = DBConn.getConn();
        String sql = "insert into news values(null,?,?,?,?)";
        try {
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setString(1, news.getNewsTitle());
            pmst.setString(2, news.getNewsContent());
            pmst.setString(3, (new Date()).toString());
            pmst.setString(4, news.getAdminName());
            return pmst.executeUpdate(sql); // 执行添加 返回受影响的行数
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 更新功能
     * @param news
     * @return
     */
    public int update(NewsBeam news){
        Connection conn = DBConn.getConn();
        String sql = "update news set NewsTitle=?, NewsContent=?, NewsTime=?, AdminName=? where NewsID=?";
        try {
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setString(1, news.getNewsTitle());
            pmst.setString(2, news.getNewsContent());
            pmst.setString(3, (new Date()).toString());
            pmst.setString(4, news.getAdminName());
            pmst.setInt(5, news.getNewsID());
            return pmst.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int delete(int newsID){
        Connection conn = DBConn.getConn();
        try {
            String sql = "delete from news where NewsID=?";
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setInt(1, newsID);
            return pmst.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
